var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../common/common');
var DBConfig = require('../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);

//获取规则列表
router.get('/jkyx/pc/coupon-rule-list',function(req,res,next){
    pool.getConnection(function(err, connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        let coutSql = 'select count(*) as totalCount from coupon_rule';
        connection.query(coutSql,function(err, result){
            
            if (err){
                res.end(JSON.stringify({
                   msg: '数据库查询失败',
                   status:'102',
                   err: err
               }));
            }else{
                var totalCount = result[0].totalCount,page = Number(req.query.page),limit = req.query.limit || 20;
                var totalPage = Math.ceil(totalCount/limit);
                if(page)
                {
                    var limitStart = Number(page-1)*limit,limitEnd = page*limit;
                }else
                {
                    var limitStart = 0,limitEnd = totalCount;
                }
                connection.query(DBConfig.couponRulsList,[limitStart,limitEnd],function(err, result){
                    connection.release();
                    if (err){
                        res.end(JSON.stringify({
                           msg: '数据库查询失败',
                           status:'102',
                           err: err
                       }));
                    }else{
                        var newArray = [];
                        result.forEach((data,index) => {
                            data.rule_param = JSON.parse(data.param);
                            data.id = Number(data.id);
                            data.add_time = CommonJS.getNowFormatDate(data.add_time);
                            data.update_time = CommonJS.getNowFormatDate(data.update_time);
                            newArray[index] = data;
                        });
                        res.end(JSON.stringify({
                            status:100,
                            page:page,
                            limit:limit,
                            totalCount:totalCount,
                            data:newArray
                        }));
                    }
                });
            }
            
        });
        
    });
});

//添加规则
router.get('/jkyx/pc/add-coupon-rule', function(req, res, next){
    var param = req.query || req.params; 
    pool.getConnection(function(err, connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
        }
        let name = param.name,type=param.type,addTime = CommonJS.getNowFormatDate(),use_type = param.use_type,goods_id = param.goods_id || '';
        connection.query(DBConfig.addCouponRules,[name,type,JSON.stringify(param.rule_param),addTime,use_type,goods_id],function(err, result){
            connection.release();
            if (err){
                res.end(JSON.stringify({
                   msg: '数据库查询失败',
                   status:'102',
                   err: err
               }));
          }else{
              res.end(JSON.stringify({
                  status:100,
                  msg:"提交成功"
              }));
          }
          
        });
    });
});

//修改优惠券规则
router.get('/jkyx/pc/coupon-rule-update', function(req, res, next){
	var param = req.query || req.params; 
	var id = param.id || '';
//  let param = req.body,id=req.body.id || '';
    pool.getConnection(function(err, connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
        }
        let  name = param.name,type=param.type,updateTime = CommonJS.getNowFormatDate(),use_type = param.use_type,goods_id = param.goods_id || '';
        connection.query(DBConfig.updateCouponRules,[name,type,param.rule_param,updateTime,use_type,goods_id,id,id],function(err, result){
            connection.release();
            if (err){
                res.end(JSON.stringify({
                   msg: '数据库查询失败',
                   status:'102',
                   err: err
               }));
          }else{
              data = result[1][0];
              res.end(JSON.stringify({
                'status':100,  
                'id':id,
                'name':data.name,
                'rule_param':JSON.parse(data.param),
                'add_time':CommonJS.getNowFormatDate(data.add_time),
                'update_time':CommonJS.getNowFormatDate(data.update_time)
            }));
          }
        });
    });
});

//删除优惠券规则
router.get('/jkyx/pc/coupon-rule-del', function(req, res, next){
    let id=req.query.id || '';
    pool.getConnection(function(err, connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
        }

        connection.query(DBConfig.deleteCouponRule,[id],function(err, result){
            connection.release();
            if (err){
                res.end(JSON.stringify({
                   msg: '删除失败',
                   status:'102',
                   err: err
               }));
          }else{
              res.end(JSON.stringify({
                status:'100',
                msg:"删除成功"
            }));
          }
          
        });
    });
});

//获取一条规则
router.get('/jkyx/pc/coupon-rule', function(req, res, next){
    let id=req.query.id || '';
    pool.getConnection(function(err, connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
        }

        connection.query(DBConfig.getOneCouponRule,[id],function(err, result){
            connection.release();
            if (err){
                res.end(JSON.stringify({
                   msg: '删除失败',
                   status:'102',
                   err: err
               }));
          }else{
              res.end(JSON.stringify({
                status:100,
                data:{
                    id:id,
                    type:result[0].type,
                    name:result[0].name,
                    param:JSON.parse(result[0].param)
                }
            }));
          }
        });
    });
});


module.exports = router;